<template>
  <VDialog @close="handleClose" @save="save" :loading="loading" width="50%">
    <template #content>
      <div class="max-h-[75vh]">
        <el-form
          ref="formRef"
          label-position="top"
          :model="formValues"
          :rules="rules"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="英文名" prop="en_name">
                <el-input
                  v-model="formValues.en_name"
                  placeholder="请输入英文名"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="真实姓名" prop="realname">
                <div class="flex w-[100%]">
                  <el-input
                    v-model="formValues.realname"
                    placeholder="请输入真实姓名"
                    class="w-[100%]"
                  />
                  <el-switch
                    v-model="formValues.status"
                    inline-prompt
                    active-text="启用"
                    inactive-text="禁用"
                    :active-value="1"
                    :inactive-value="0"
                    class="ml-[16px]"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="formValues.mobile" />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工号" prop="employee_no">
                <el-input
                  v-model="formValues.employee_no"
                  type="text"
                  :disabled="isEdit"
                  placeholder="请输入工号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  v-model="formValues.birthday"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择生日"
                  class="w-[100%]"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="登陆密码" prop="password">
            <el-input
              v-model="formValues.password"
              placeholder="默认为空,不修改密码"
            />
          </el-form-item>
          <el-form-item label="所属部门" prop="department">
            <div class="bg-[var(--base-small-bg-color)] p-[10px] w-[100%]">
              <template
                v-for="(item, index) in formValues.department"
                :key="index"
              >
                <div>{{ `所属部门${index + 1}` }}</div>
                <div class="flex w-[100%] items-center">
                  <el-cascader
                    v-model="item.department_id"
                    :options="menuList"
                    :props="cascaderProps"
                    filterable
                    class="w-[70%]"
                  />
                  <span class="ml-[16px] w-[90px]">部门负责人</span>
                  <el-switch
                    v-model="item.is_department_head"
                    :active-value="1"
                    :inactive-value="0"
                  ></el-switch>
                  <span class="w-[2rem] ml-[16px]">
                    <SvgIcon
                      icon-class="Plus"
                      class="text-[12px]"
                      @click="handleAddDept"
                    />
                  </span>
                  <span class="w-[2rem]">
                    <SvgIcon
                      @click="handleRemoveDept(index)"
                      v-if="index !== 0"
                      icon-class="Minus"
                      class="text-[12px]"
                    />
                  </span>
                </div>
              </template>
            </div>
          </el-form-item>
          <el-form-item label="角色" prop="icon">
            <el-input
              class="search mb-[10px]"
              v-model="roleName"
              size="large"
              placeholder="角色名称"
              prefix-icon="Search"
              clearable
            />
            <template v-for="item in roleListData" :key="item.id">
              <el-tag
                class="mb-[10px] mx-[0.25rem] text-[var(--base-text-color)] text-[14px] cursor-pointer"
                v-if="item.status"
                :type="formValues.role_ids.includes(item.id) ? '' : 'info'"
                :effect="
                  formValues.role_ids.includes(item.id) ? 'light' : 'plain'
                "
                size="large"
                round
                @click="handleSelectRole(item.id)"
              >
                {{ item.name }}
              </el-tag>
            </template>
          </el-form-item>
        </el-form>
      </div>
    </template>
  </VDialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import SvgIcon from "@/components/SvgIcon/index.vue";
import api from "../../api/index";
import { roleList } from "@/api/system/role";
import { debounce } from "@/utils/tools.js";
const props = defineProps({
  menuList: {
    type: Array,
    default: [],
  },
  id: { type: [Number, String], default: "" },
});
const { menuList } = toRefs(props);
const isEdit = computed(() => !!props.id);
watch(
  () => props.id,
  async (val) => {
    if (!val) return;
    const { data } = await api.userDetail({ id: val });
    for (let key in formValues.value) {
      formValues.value[key] = data[key];
    }
  }
);
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const loading = ref(false);
const formRef = ref();

const cascaderProps = {
  children: "sub",
  label: "name",
  value: "id",
  checkStrictly: true,
  emitPath: false,
};
const formValues = ref({
  id: null,
  en_name: null,
  realname: null,
  status: 0,
  mobile: null,
  employee_no: null,
  birthday: null,
  password: null,
  department: [
    {
      department_id: "",
      is_department_head: "0",
    },
  ],
  role_ids: [],
});
//手机号验证
const checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("手机号不能为空"));
  }
  const mobileReg = /^1[3-9]\d{9}$/;
  const landlineReg = /^\d{3}-\d{8}$|^\d{4}-\d{7}$/;
  if (mobileReg.test(value) || landlineReg.test(value)) {
    return callback();
  } else {
    return callback(new Error("请输入正确的联系电话"));
  }
};
const rules = reactive({
  en_name: [{ required: true, message: "英文名不能为空", trigger: "blur" }],
  realname: [{ required: true, message: "中文名不能为空", trigger: "blur" }],
  mobile: [{ required: true, validator: checkPhone, trigger: "blur" }],
  department: [
    { required: true, message: "所属部门不能为空", trigger: "change" },
  ],
  employee_no:[{ required: true, message: "工号不能为空!", trigger: "blur" }]
});
const handleRemoveDept = (index) => {
  formValues.value.department.splice(index, 1);
};
const handleAddDept = () => {
  formValues.value.department.push({
    department_id: "",
    is_department_head: "0",
  });
};
const roleListData = ref([]);
const roleListDataAll = ref([]);
const getroleList = async () => {
  const { data } = await roleList({ pageNum: 1, pageSize: 1000 });
  roleListData.value = data || [];
  roleListDataAll.value = data || [];
};
getroleList();
const handleSelectRole = (id) => {
  const roleIndex = formValues.value.role_ids.indexOf(id);
  if (roleIndex >= 0) {
    formValues.value.role_ids.splice(roleIndex, 1);
  } else {
    formValues.value.role_ids.push(id);
  }
};
const save = async () => {
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        let department = formValues.value?.department?.filter(
          (item) => item.department_id !== ""
        );
        if (!department?.length) return ElMessage.warning("所属部门不能为空!");
        loading.value = true;
        const { code, message } = await (formValues.value?.id
          ? api.userUpdate
          : api.userCreate)(formValues.value);
        if (code !== 200) return ElMessage.error(message);
        ElMessage.success("保存成功!");
        handleClose(true);
      } catch (error) {
      } finally {
        loading.value = false;
      }
    }
  });
};

const roleName = ref('')
const updateRoleList = debounce((val) => {
  const keyword = val.trim().toLowerCase();
  roleListData.value = keyword
    ? roleListDataAll.value.filter((e) =>
        e.name.toLowerCase().includes(keyword)
      )
    : roleListDataAll.value;
}, 300);
watch(
  () => roleName.value,
  (val) => {
    updateRoleList(val);
  }
);

const handleClose = async (refresh) => {
  formValues.value = {
    id: null,
    en_name: null,
    realname: null,
    status: 0,
    mobile: null,
    employee_no: null,
    birthday: null,
    password: null,
    department: [
      {
        department_id: "",
        is_department_head: "0",
      },
    ],
    role_ids: [],
  };
  roleName.value = ''
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style lang="scss" scoped>
:deep(.el-tag--light) {
  border-color: #3487ff;
  background-color: var(--base-primary-bg);
  .el-tag__content {
    color: #3487ff;
  }
}
.search {
  box-sizing: content-box;
  border: none;

  &:deep(.el-input__wrapper) {
    padding: 1px 15px;
    box-shadow: none;
    background-color: var(--base-small-bg-color);
  }
}
</style>
